package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.UserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;


@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(UserDTO dto) {
//        验证参数
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        密码检查
        AdUser user = this.getOne(new LambdaQueryWrapper<AdUser>().eq(AdUser::getName, dto.getName()));
        String encodeWithSalt = MD5Utils.encodeWithSalt(dto.getPassword(), user.getSalt());
        if (user.getPassword().equals(encodeWithSalt)){
//            用户状态检查
            Integer status = user.getStatus();
            if (status != 9){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
            }
//            更新登录时间
            user.setLoginTime(new Date());
            updateById(user);
//            颁发token
            String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
            AdUserVO userVO = new AdUserVO(user);
            HashMap<String, String> map = new HashMap<>();
            map.put("token", token);
            map.put("user", JSON.toJSONString(userVO));
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
}
